dojo.provide("demo.grid.FixedTreeGrid");

dojo.require("dojox.grid.TreeGrid");

dojo.declare("demo.grid.FixedTreeGrid", dojox.grid.TreeGrid, {
    /* @Override */
    getItem: function(/*integer|Array|String*/ idx) {
        // summary:
        //      Overridden to fix a treeModel.childrenAttrs bug.
        var isArray = dojo.isArray(idx);
        if (dojo.isString(idx) && idx.indexOf("/")) {
            idx = idx.split("/");
            isArray = true;
        }
        if (isArray && idx.length === 1) {
            idx = idx[0];
            isArray = false;
        }
        if (!isArray) {
            return dojox.grid.DataGrid.prototype.getItem.call(this, idx);
        }
        var s = this.store;
        var itm = dojox.grid.DataGrid.prototype.getItem.call(this, idx[0]);
        var cf;
        if (this.aggregator) {
            cf = this.aggregator.childFields || [];
        }else if (this.treeModel) {
            cf = this.treeModel.childrenAttrs || [];
        }
        if (cf) {
            var childrenAttr = cf[0];
            for (var i = 0; i < idx.length - 1 && itm; i++) {
                if (childrenAttr) {
                    itm = (s.getValues(itm, childrenAttr) || [])[idx[i + 1]];
                }else{
                    itm = null;
                }
            }
        }
        return itm || null;
    },

    /* @Override */
    onKeyDown: function(e) {
        var dk = dojo.keys;

        switch(e.keyCode) {
            case dk.SPACE: // Add SPACE event to fix cannot press space key to toggle checkbox under IE.
                if (!this.edit.isEditing()) {
                    colIdx = this.focus.getHeaderIndex();
                    if (colIdx >= 0) {
                        this.setSortIndex(colIdx);
                        break;
                    } else {
                        this.selection.clickSelect(this.focus.rowIndex, dojo.isCopyKey(e), e.shiftKey);
                    }
                    //dojo.stopEvent(e); // This line causes cannot press space key to toggle checkbox under IE.
                }
                break;
            default:
                this.inherited(arguments);
                break;
        }
    },

    getRootRowIndex: function(/*Integer|Array|String*/idx) {
        // summary:
        //      overridden so that you can pass in a "/" delimited string of indexes to get the
        //      item based off its path...that is, passing in "1/3/2" will get the
        //      3rd (0-based) child from the 4th child of the 2nd top-level item.
        var isArray = dojo.isArray(idx);
        if (dojo.isString(idx) && idx.indexOf("/")) {
            idx = idx.split("/");
            isArray = true;
        }
        if (isArray && idx.length == 1) {
            idx = idx[0];
            isArray = false;
        }

        var rootRowIndex = isArray ? idx[0] : idx;
        return rootRowIndex;
    }

});
